package com.credithc.customers.dataservice.service.impl;

import com.credithc.baseserv.core.utils.UUIDUtils;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.constants.ProductTypeConstants;
import com.credithc.customers.base.mapper.CustomerRelationInfoMapper;
import com.credithc.customers.base.po.CustomerRelationInfoPo;
import com.credithc.customers.dataservice.Thread.OldDataThreadPoolExecutor;
import com.credithc.customers.dataservice.constants.SyncTypeEnum;
import com.credithc.customers.dataservice.mapper.BDB.*;
import com.credithc.customers.dataservice.po.*;
import com.credithc.customers.dataservice.ro.CustomerProductInfoRo;
import com.credithc.customers.dataservice.ro.ProductInfoRo;
import com.credithc.customers.dataservice.service.OldBDBataService;
import com.credithc.customers.dataservice.service.SyncDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Slf4j
public class OldBDBataServiceImpl implements OldBDBataService {
    @Autowired
    private HrhbProductMapper hrhbProductMapper;
    @Autowired
    private SyncDataService syncDataService;
    @Autowired
    private HrhbOrderInSureMappper hrhbOrderInSureMappper;
    @Autowired
    private OldDataThreadPoolExecutor oldDataThreadPoolExecutor;
    @Autowired
    private HrhbOrderToCustomMapper hrhbOrderToCustomMapper;
    @Autowired
    private HhrbCustomMapper hhrbCustomMapper;
    @Autowired
    private YztCustomMapper yztCustomMapper;
    @Autowired
    private HrhbSubOrderMapper hrhbSubOrderMapper;
    @Autowired
    private CustomerRelationInfoMapper customerRelationInfoMapper;
    @Override
    public void oldOrder(Integer start) {
        boolean f =true;
        Long num = null;
        if (start != null && start>0) {
            num = Long.valueOf(start);
        }else{
            num = hrhbOrderInSureMappper.queryOrderMaxId();
        }
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.execute(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    Example example = new Example(BDBInSurePO.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andBetween("id",vernier.get()-10000,vernier.get());
                    List<BDBInSurePO> bdbInSurePOS = hrhbOrderInSureMappper.selectByExample(example);
                    if (bdbInSurePOS.size() > 0) {
                        bulidBdbOrder(bdbInSurePOS);
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            });
            f = OldHyrDataServiceImpl.exit(f, vernier, e);
        }
    }

    private void bulidBdbOrder(List<BDBInSurePO> bdbInSurePOS) {
        int i =0;
        for (BDBInSurePO b:bdbInSurePOS) {
            if (StringUtils.isNotBlank(b.getPolicyNo())) {
                CustomerProductInfoRo customerProductInfoRo = new CustomerProductInfoRo();
                customerProductInfoRo.setDatabaseName("hrhbbx");
                customerProductInfoRo.setTableName("hrhb_order_insure");
                customerProductInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
                customerProductInfoRo.setSystemSign("BX");
                customerProductInfoRo.setSubSystemSign("BDB");
                customerProductInfoRo.setProductStatus(6);
                customerProductInfoRo.setProductSourceSystem("19");
                customerProductInfoRo.setProductStartTime(b.getStartdate());
                customerProductInfoRo.setProductEndTime(b.getEnddate());
                if (customerProductInfoRo.getProductStartTime()!=null && customerProductInfoRo.getProductEndTime() != null){
                    int deadLine = (int) ((customerProductInfoRo.getProductEndTime().getTime() - customerProductInfoRo.getProductStartTime().getTime()) / (1000 * 3600 * 24));
                    customerProductInfoRo.setProductDeadline(deadLine + "");
                }


                String order_no =b.getOrderNo();
                Example orderToCustomE = new Example(HrhbOrderToCustomPO.class);
                Example.Criteria orderToCustomCriteria = orderToCustomE.createCriteria();
                orderToCustomCriteria.andEqualTo("orderno",order_no);
                List<HrhbOrderToCustomPO> hrhbOrderToCustomPOS = hrhbOrderToCustomMapper.selectByExample(orderToCustomE);
                for (HrhbOrderToCustomPO h:hrhbOrderToCustomPOS) {
                    Example hrhbCustomE = new Example(HhrbCustomPO.class);
                    Example.Criteria hrhbCustomC = hrhbCustomE.createCriteria();
                    hrhbCustomC.andEqualTo("customcode",h.getCustomcode());
                    HhrbCustomPO hhrbCustomPO = hhrbCustomMapper.selectOneByExample(hrhbCustomE);
                    if (hhrbCustomPO!= null) {
                        Example yztCustomE = new Example(YztCustomPO.class);
                        Example.Criteria yztCustomC = yztCustomE.createCriteria();
                        yztCustomC.andEqualTo("idno", hhrbCustomPO.getIdno());
                        YztCustomPO yztCustomPO = null;
                        try {
                            yztCustomPO = yztCustomMapper.selectOneByExample(yztCustomE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if(yztCustomPO != null ) {
                            h.setCustomNo(yztCustomPO.getCustomNo());
                        }
                    }
                }
                Example subOrderE = new Example(HrhbSubOrderPO.class);
                Example.Criteria subOrderC = subOrderE.createCriteria();
                subOrderC.andEqualTo("orderno",order_no);
                List<HrhbSubOrderPO> hrhbSubOrderPOS = hrhbSubOrderMapper.selectByExample(subOrderE);
                List<HrhbOrderToCustomPO> tb = new ArrayList<>();
                List<HrhbOrderToCustomPO> bb = new ArrayList<>();
                for (HrhbSubOrderPO h:hrhbSubOrderPOS) {
                    for (HrhbOrderToCustomPO o:hrhbOrderToCustomPOS) {
                        if ("01".equals(o.getRelationtype())){
                            customerProductInfoRo.setCustomerRole("3");
                            customerProductInfoRo.setUserResourceId(o.getCustomcode());
                            customerProductInfoRo.setCustomerNo(o.getCustomNo());
                            customerProductInfoRo.setProductAmount(new BigDecimal(h.getFee()));
                            customerProductInfoRo.setProductNo(h.getProductcode());
                            if (StringUtils.isNotBlank(customerProductInfoRo.getCustomerNo())) {
                                customerProductInfoRo.setTableKey("s"+b.getId()+"o"+h.getId()+"c"+o.getId());
                                syncDataService.syncCustomerProduct(customerProductInfoRo);
                                tb.add(o);
                            }

                        }else if ("02".equals(o.getRelationtype())){
                            if (StringUtils.isNotBlank(o.getCustomNo())) {
                                syncDataService.addRoleInfo(o.getCustomcode(), o.getCustomNo(), "BX", "BDB", "4", CustomerConstants.CUSTOMER_ROLE_EFFECTIVE);
                                bb.add(o);
                            }

                        }
                    }
                }
                //添加关系
                for (HrhbOrderToCustomPO tbr: tb) {
                    for (HrhbOrderToCustomPO bbr:bb) {
                        CustomerRelationInfoPo customerRelationInfoPo = new CustomerRelationInfoPo();
                        customerRelationInfoPo.setRelationId("tb"+tbr.getCustomcode()+"bb"+bbr.getCustomcode());
                        customerRelationInfoPo.setCustomerNo(tbr.getCustomNo());
                        customerRelationInfoPo.setRoleInRelation(2);
                        CustomerRelationInfoPo customerRelationInfoPo1 = customerRelationInfoMapper.selectOne(customerRelationInfoPo);
                        if (customerRelationInfoPo1 == null) {
                            customerRelationInfoPo.setId(UUIDUtils.getUUID());
                            customerRelationInfoPo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            customerRelationInfoPo.setSubSystemSign("BDB");
                            customerRelationInfoPo.setSystemSign("BX");
                            customerRelationInfoPo.setRelationId("tb"+tbr.getCustomcode()+"bb"+bbr.getCustomcode());
                            customerRelationInfoPo.setRelationSource(2);
                            customerRelationInfoPo.setRoleInRelation(2);
                            try {
                                customerRelationInfoMapper.insert(customerRelationInfoPo);
                            } catch (Exception e) {
                               // e.printStackTrace();
                            }
                        }
                        customerRelationInfoPo.setRoleInRelation(3);
                        customerRelationInfoPo.setCustomerNo(bbr.getCustomNo());
                        CustomerRelationInfoPo customerRelationInfoPo2 = customerRelationInfoMapper.selectOne(customerRelationInfoPo);
                        if (customerRelationInfoPo2 == null) {
                            customerRelationInfoPo.setId(UUIDUtils.getUUID());
                            customerRelationInfoPo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            customerRelationInfoPo.setSubSystemSign("BDB");
                            customerRelationInfoPo.setSystemSign("BX");
                            customerRelationInfoPo.setRelationId("tb"+tbr.getCustomcode()+"bb"+bbr.getCustomcode());
                            customerRelationInfoPo.setRelationSource(2);
                            customerRelationInfoPo.setRoleInRelation(3);
                            try {
                                customerRelationInfoMapper.insert(customerRelationInfoPo);
                            } catch (Exception e) {
                               // e.printStackTrace();
                            }
                        }
                    }
                }

            }
        }
    }

    @Override
    public void oldProduct( Integer start) {
        boolean f =true;
        Long num = null;
        if (start != null && start >0) {
            num = Long.valueOf(start);
        }else{
            num = hrhbProductMapper.queryProductMaxId();
        }
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.execute(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    Example example = new Example(BdbProductPo.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andBetween("id",vernier.get()-10000,vernier.get());
                    List<BdbProductPo> systemUserPos = hrhbProductMapper.selectByExample(example);
                    if (systemUserPos.size() > 0) {
                        bulidBdbProduct(systemUserPos);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = OldHyrDataServiceImpl.exit(f, vernier, e);
        }
    }

    private void bulidBdbProduct(List<BdbProductPo> systemUserPos) {
        for (BdbProductPo b:systemUserPos) {
            ProductInfoRo productInfoRo = new ProductInfoRo();
            productInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            productInfoRo.setDatabaseName("bdt");
            productInfoRo.setTableName("hrhb_productdef");
            productInfoRo.setProductChannel(CustomerConstants.BDB);
            productInfoRo.setSubSystemSign(CustomerConstants.BDB);
            productInfoRo.setSystemSign(CustomerConstants.BX);
            productInfoRo.setProductType(Integer.toString(ProductTypeConstants.INSURANCE));
            productInfoRo.setProductNo(b.getProductcode());
            productInfoRo.setTableKey(b.getId()+"");
            productInfoRo.setProductName(b.getProductname());
            productInfoRo.setProductCreateTime(b.getCreateTime());
            syncDataService.syncProduct(productInfoRo);
        }
    }
}
